package cn.zpro.zookeeper.homework;

import cn.zpro.zookeeper.model.UserCenter;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.zookeeper.CreateMode;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 使用zookeeper实现master选举（多进程模型）
 * curator 方式
 */
public class MasterSelecter {
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    private CuratorFramework curatorFramework;

    private PathChildrenCacheListener pathChildrenCacheListener;

    private UserCenter master;

    private final static String MASTER_PATH = "/master"; //需要争抢的节点

    private static boolean isRunning = false;

    private UserCenter server;


    public MasterSelecter() {

    }

    /**
     * 构造器
     *
     * @param curatorFramework
     */
    MasterSelecter(CuratorFramework curatorFramework, UserCenter server) throws Exception {
        this.curatorFramework = curatorFramework;
        this.server = server;
        this.pathChildrenCacheListener = new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                switch (pathChildrenCacheEvent.getType()) {
                    case CHILD_ADDED:
                        System.out.println("增加子节点");
                        break;
                    case CHILD_REMOVED:
                        select();
                        break;
                    case CHILD_UPDATED:
                        System.out.println("更新子节点");
                        break;
                    default:
                        break;
                }
            }
        };

        System.out.println("[" + server + "] 去争抢master权限");
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, "/event", true);
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
    }

    public static void main(String[] args) {
        new MasterSelecter().test();

    }

    void test() {
        scheduledExecutorService.scheduleWithFixedDelay(() -> {
            System.out.println("每隔5秒执行一次");
        }, 0, 5, TimeUnit.SECONDS);
    }

    /**
     * 选举方法
     */
    void select() throws Exception {
        System.out.println("开始选举");
        try {
            curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(MASTER_PATH);
            master=server; //把server节点赋值给master
            System.out.println(master+"->我现在已经是master，你们要听我的");
            //定时器
            //master释放(master 出现故障）,没5秒钟释放一次
           scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
               @Override
               public void run() {
                   try {
                       releaseMaster();
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }, 0, 5, TimeUnit.SECONDS);

        }catch (Exception e){
            //表示master已经存在
            UserCenter userCenter = (UserCenter) ByteToObject(curatorFramework.getData().forPath(MASTER_PATH));

            if(userCenter==null) {
                System.out.println("启动操作：");
                select();//再次获取master
            }else{
                master=userCenter;
            }
        }

    }

    /**
     * 启动选举
     */
    void start() throws Exception {
        System.out.println("启动选举方法");
        //开始选举
        if (!isRunning) {
            isRunning = true;
            PathChildrenCache pathChildrenCache =
                    new PathChildrenCache(curatorFramework,MASTER_PATH,false);
            pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
            select();
        }

    }

    /**
     * 释放资源
     */
    void releaseMaster(){
        //释放锁(故障模拟过程)
        //判断当前是不是master，只有master才需要释放
        if (checkIsMaster()) {
            try {
                curatorFramework.delete().forPath("/event"); //删除
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private boolean checkIsMaster() {
        //判断当前的server是不是master
        UserCenter userCenter = null;
        try {
            userCenter = (UserCenter) ByteToObject(curatorFramework.getData().forPath("/event"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (userCenter.getMc_name().equals(server.getMc_name())) {
            master = userCenter;
            return true;
        }
        return false;
    }


     static Object ByteToObject(byte[] bytes) {
        Object obj = null;
        try {
            // bytearray to object
            ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
            ObjectInputStream oi = new ObjectInputStream(bi);

            obj = oi.readObject();
            bi.close();
            oi.close();
        } catch (Exception e) {
            System.out.println("translation" + e.getMessage());
            e.printStackTrace();
        }
        return obj;
    }


}
